package be.ac.ua.pats.thesisrobotica.robot.RR.sensors;

//~--- non-JDK imports --------------------------------------------------------

import be.ac.ua.pats.thesisrobotica.robot.RR.sensors.listeners.Listenable;
import be.ac.ua.pats.thesisrobotica.robot.RR.sensors.listeners.threads.ListenerThread;
import be.ac.ua.pats.thesisrobotica.robot.communication.Connection;
import be.ac.ua.pats.thesisrobotica.robot.RR.sensors.utils.IdFactory;
import be.ac.ua.pats.thesisrobotica.robot.RR.sensors.utils.SensorNotification;
import be.ac.ua.pats.thesisrobotica.robot.exceptions.InitializationException;
import lejos.nxt.comm.RConsole;

/**
 * @author Jimmy
 */
public abstract class Sensor extends Listenable {

    protected String             id;
    protected boolean            initialized;
    protected SensorNotification sensorNotification;
    protected String             type;
        boolean connected = false;
        boolean notifications = false;

    public Sensor() {
        this(null);
    }

    public Sensor(Connection connection) {
        if(connection != null) {
            sensorNotification = new SensorNotification(connection,this.id);
            connected = true;
        }
        this.id         = IdFactory.generate();
    }

    @Override
        public void startListening() {
        RConsole.println("start listening");
        startTimer();
        RConsole.println("oh yea");
        ListenerThread.get().addSensor(this);
    }

    public abstract int getRealValue() throws InitializationException;

    public abstract String getValue() throws InitializationException;

    public void setNotifications(boolean b) {
        this.notifications = b;
    }

    @Override
    public void stateChanged(int value) {
        if (connected && notifications) {
            sensorNotification.setAndSend(String.valueOf(value));
        } else {
            RConsole.println(this.getType()+": Not connected or no notifications requested: " + value);
        }
    }

    public void setConnection(Connection connection) {
            sensorNotification = new SensorNotification(connection,this.id);
            connected = true;
    }

    public String getType() {
        return type;
    }

    public String getId() {
        return id;
    }
}
